Tuesday, January 12, 2010

Use Find Method of Generic List

Is there a quick way to Find an object in a List<T> without looping through the List or using Linq? Yes; use the Find Method of the object.

If you are new to .NET, or even if you have been using it for years, but you still have outdated ways of doing things, you might be waisting developement time, resources, and performance if you do not keep up to date on new features that the .NET framework brings to the table for algorithms that you use all the time.

For example, if you need to find an object in a generic List<T>, you might still be using code like the code shown below. Suppose that you have a List<Address> and the Address object has an IsPrimary field (bool). One and only one of the objects can be primary and you need to retrieve the primary address object from the List. The "user" object has an Addressess property which is a List<Address>. The tried and proven (over and over) method for doing this would be:

   Address primaryAddress;


   foreach (Address addr in user.Addresses)
   {
       if (addr.IsPrimary)
       {
         primaryAddress = addr;
         break;
       } // if
   } // foreach


Obviously, the code shown above works just fine. But, consider the following line of code that will achieve the same result.


   Address primaryAddr =
   user.Addresses.Find(delegate(Address obj)
      { return obj.IsPrimary; });


Passing a Delegate to the Find method of the generic List<Address> finds the object that has the IsPrimary field set to true with a single line of code.

Just another shortcut that hopefully will save you some time.

Need to automatically organize your code windows? You'll be amazed how easy it is to keep the code in your code windows organized. TRY IT FREE FOR 30 DAYS BY CLICKING HERE.



Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily. Try CSharpCompleter for 30 DAYS FREE.



You can also email me directly at les@KnowDotNet.com.

0 Comments:

Post a Comment

<< Home